package com.cloudshadow.platform.server.common.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudshadow.platform.infrastructure.core.service.CoreService;
import com.cloudshadow.platform.infrastructure.exception.ErrorInfos;
import com.cloudshadow.platform.server.common.base.model.BaseModel;
import com.cloudshadow.platform.server.common.base.req.PageReq;
import com.cloudshadow.platform.server.common.base.service.BaseServiceImpl;
import com.cloudshadow.platform.server.common.base.utils.VoUtil;
import com.cloudshadow.platform.server.common.base.vo.BasicVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by apple on 17/3/5.
 */
public abstract class BaseController<S extends BaseServiceImpl, T extends BaseModel> extends CoreService {

    private Class<S> serverClass;
    private Class<T> tClass;

    protected BaseController(){
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        serverClass = (Class) params[0];
        tClass = (Class) params[1];
    }

    @Autowired
    protected S server;


    /**
     * 入参转实体
     * @return
     */
    protected T changeEntity(Object obj){
        JSONObject jsonObj = (JSONObject) JSON.toJSON(obj);
        T entity = (T) JSONObject.toJavaObject(jsonObj, tClass);
        return entity;
    }

    /**
     * 入参转实体
     * @return
     */
    protected PageReq changePage(JSONObject req){
        return (PageReq) JSONObject.toJavaObject(req, PageReq.class);
    }


    /**
     * 获取分页查询值
     * @param pageReq
     * @return
     */
    protected Page<T> getPage(PageReq pageReq){
        T entity = changeEntity(pageReq);
        return server.findByPage(
                entity
                , pageReq.getPageNo()
                , pageReq.getPageSize(),
                pageReq.getSort() == null ? null : new Sort(pageReq.getSort()));
    }


    protected BasicVo<T> getFallback(PageReq form){
        return VoUtil.genErrorResult(ErrorInfos.CommonErr.SERVER_NOT_EXIST.getError_no(), ErrorInfos.CommonErr.SERVER_NOT_EXIST.getError_info(),BasicVo.class);
    }
}
